package com.etheart.lyric.htmlparser.action.parse;

import java.io.File;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.etheart.framework.core.dao.CrudService;
import com.etheart.framework.core.util.RegexUtils;
import com.etheart.lyric.htmlparser.util.HttpDownloader;
import com.etheart.lyric.htmlparser.util.LyricParseUtils;
import com.etheart.model.entity.Album;
import com.etheart.model.entity.Singer;
import com.etheart.model.entity.Song;
import com.etheart.music.service.AlbumService;
import com.etheart.music.service.SingerService;
import com.etheart.music.service.SongService;

public class DownLyricThread extends Thread  {
	private static final Log logger = LogFactory.getLog(DownLyricThread.class);
	private long startSongId=0;
	private long endSongId = 0;     
	private String mirrorPath = "D:\\qqmusic\\巨鲸\\mirror";
	private String savePath="lyric";
	                           
	private SongService songService;                          
	private SingerService singerService;
	private AlbumService albumService;
	private CrudService crudService;
	public DownLyricThread(long startSongId,long endSongId,SongService songService,SingerService singerServce,AlbumService albumService,CrudService crudService,String mirrorPath,String savePath) {
		super();  
		this.startSongId = startSongId;
		this.endSongId = endSongId;
		this.songService = songService;
		this.singerService=singerServce;
		this.albumService=albumService;
		this.crudService = crudService;
		this.mirrorPath = mirrorPath == null? this.mirrorPath:mirrorPath;
		this.savePath = savePath == null ? this.savePath:savePath;
	}
	public DownLyricThread() {
		
	}
	@Override
	public void run() {
		HibernateTemplate template = (HibernateTemplate) crudService.getDelegate();
		Session session =template.getSessionFactory().openSession();
	//	template.getSessionFactory().getCurrentSession();
		//Session session = getSession(sessionFactory);
		TransactionSynchronizationManager.bindResource(template.getSessionFactory(), new SessionHolder(session));
		HttpDownloader downloader = new HttpDownloader();
		for (long i = startSongId; i < endSongId; i++) {  
			Song song = songService.findById(i);      
			if (song ==null ||( StringUtils.isNotBlank(song.getLrcContent())&&StringUtils.isNotBlank(""))) {
				continue;    
			}                       
			//开始down歌词
			//http://lyric.top100.cn/Special_120699/M0120699006.lrc
			Album album = albumService.findById(song.getAlbum().getId());
			if (album == null || album.getPicture() ==null) {
				continue;
			}
			//"http://pic.top100.cn/SpecialImg/36/middle_special_359890.jpg"
			//http://lyric.top100.cn/s/20/Special_191364/M0191364001.lrc
			//http://lyric.top100.cn/s/1/Special_9753/M0009753018.lrc
			String specialId = RegexUtils.getMatcheGroup(".*middle_special_([0-9]*).jpg", album.getPicture());
			String folder = (Integer.parseInt(specialId)/10000+1)+"";
			String url = "http://lyric.top100.cn/s/"+folder+"/Special_"+specialId+"/"+song.getId()+".lrc";
			String url2 = "http://lyric.top100.cn/Special_"+specialId+"/"+song.getId()+".lrc";

			String lastId=String.valueOf((song.getId()%100));
			lastId = StringUtils.leftPad(lastId, 2, "0");
			String  saveRealPath = mirrorPath+"\\"+savePath+"\\"+lastId+"\\"+song.getSongname()+"-"+song.getId()+".lrc";
			File dir = new File(mirrorPath+"\\"+savePath+"\\"+lastId+"\\");
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = downloader.download(url,saveRealPath);
			if (file == null) {
				file = downloader.download(url2,saveRealPath);
				//使用备用地址下载歌词
			}
			if (file !=null) {
				//解析content
				song.setLrcUrl(savePath+"/"+song.getId()+".lrc");
				
				//	String content = FileUtils.readFileToString(file,"UTF-8");
					song.setLrcContent(LyricParseUtils.getLyricContent(file));
			
					Singer singer = singerService.findById(song.getSinger().getId());
					if (singer != null && !StringUtils.equals("", song.getFromUrl())||singer == null) {
						singer = singerService.findByFromUrl(song.getFromUrl());
						if (singer != null) {
							song.setSinger(singer);
						}
					}
					songService.updateSong(song);
				//顺带update一下歌手
			}
			
		}
		SessionFactoryUtils.closeSession(session);
	}
	public long getStartSongId() {  
		return startSongId;
	}
	public void setStartSongId(long startSongId) {
		this.startSongId = startSongId;
	}
	public long getEndSongId() {
		return endSongId;
	}
	public void setEndSongId(long endSongId) {
		this.endSongId = endSongId;
	}
	public String getMirrorPath() {
		return mirrorPath;
	}
	public void setMirrorPath(String mirrorPath) {
		this.mirrorPath = mirrorPath;
	}
	public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	public void setSongService(SongService songService) {
		this.songService = songService;
	}
	public void setSingerService(SingerService singerService) {
		this.singerService = singerService;
	}
	public void setAlbumService(AlbumService albumService) {
		this.albumService = albumService;
	}
	public void setCrudService(CrudService crudService) {
		this.crudService = crudService;
	}

	
	
	
	

}
